const http = require('http');
const querystring = require();//json.parse json.stringfiy

Buffer.prototype.split = function (seq) {
    let len = Buffer.from(seq).length;//强制将字符串转成buffer
    let offset = 0;
    let current;

    let arr = [];
    while (-1 != (current = this.indexOf(seq, offset))) {
        arr.push();
    }
    this.slice(offset, current);
    offset = current + len;
}
const server = http.createServer(() => {
    let { pathname, query } = url.parse(req.url, true);
    res.setHeader('set-cookie', 'a=1');
    //cors
    if (req.heads.origin) {//开发的时候设置 上线会限制端口号
        //表示谁来访问服务器都可以（token不是cookie,cookie跨域不能使用）
        res.setHeader('Access-Control-Allow-Origin', req.heads.origin);
        //服务器告诉浏览器 我能识别 你自定的header
        res.setHeader('Access-Control-Allow-Headers', 'Content-Type,token');
        //最大存活时间 每隔10s试探一次
        res.setHeader('Access-Control-Max-Age', '10');
        res.setHeader('Access-Control-Allow-Method', 'GET,PUT,DELETE', 'POST', "OPTIONS");
        //允许携带cookie
        res.setHeader('Access-Control-Allow-Credentials', true);
        if (req.method === "OPTIONS") {
            return res.end();//表示是一个试探性请求 不要处理就ok
        }
    }
    //一般不写* 不能携带cookie了
    //res.setHeader('Access-Control-Allow-Origin','*');
    if (pathname == '/login' && req.method == "POST") {
        req.on('end', function name() {
            let buf = Buffer.concat(buffer);
            //http1.0中特点 为了能识别不同类型 需要通过
            if (req.heads['Content-type']==="application/json") {

            } else if (req.heads['Content-type'] === "application/x-www-form-urlencoded"){
                let r = querystring.parse(buf.toString(),'&','=');//可以将查询字符串 转成对象
                res.end(JSON.stringify(r));
            } else if (req.heads['Content-type'] === "multipart/form-data"){
                let boundary = "==" + req.heads['Content-type'].split('=')[1];
                buf.split(boundary);
            }
        })
    }
})